from django.core import serializers
from django.forms import model_to_dict
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from performance.devicesoption import *
from django.core.paginator import Paginator
from .models import performanceData, gameProjects
import json
import sys, io


# Create your views here.
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
def get_connectdevice(request):
    devicedata = {}
    device = get_devices()
    if not device:
        devicedata['msg'] = FALIE
        return HttpResponse(json.dumps(devicedata), content_type='application/json')
    for i in range(len(device)):
        devicedata[i] = device[i]
    return HttpResponse(json.dumps(devicedata), content_type='application/json')


def get_getpackages(request):
    device_id = request.GET.get('device_id')
    packages_list = get_packages(device_id)
    packages = {}
    code = {}
    if packages_list:
        for i in range(len(packages_list)):
            packages[i] = packages_list[i]
        return HttpResponse(json.dumps(packages), content_type='application/json')
    else:
        code['msg'] = FALIE
        return HttpResponse(json.dumps(code), content_type='application/json')


def get_meminfo(request):
    device = request.GET.get('device')
    packagename = request.GET.get('packagename')
    if device and packagename:
        mem = get_memory(device, packagename)
        return HttpResponse(json.dumps(mem), content_type='application/json')


def get_cpuinfo(request):
    cpuinfo = {}
    device = request.GET.get('device')
    packagename = request.GET.get('packagename')
    if device and packagename:
        cpu = get_cpu(device, packagename)
        cpuinfo['processCPUTime'] = cpu[0]
        cpuinfo['CPUTime'] = cpu[1]
        return HttpResponse(json.dumps(cpu), content_type='applicatin/json')


def performance(request):
    return render(request, 'performance.html')


def upload_data(request):
    p_data = request.body.decode('utf-8')
    print(p_data)
    performanceData.objects.create(data=p_data)
    dic = {'status': 100, 'msg': 'success'}
    return HttpResponse(json.dumps(dic))


def index(request):
    performance_datas = performanceData.objects.all()
    performance_datas_list = performance_datas.order_by("create_time")
    tasknames = gameProjects.objects.all().order_by("project_name")
    for i in range(0, len(performance_datas)):
        # todo 记录为空的情况要说明一下
        if performance_datas[i].data is None:
            _id = performance_datas[i].id
            performanceData.objects.get(id=_id).delete()  # 删除空数据记录
    pages = Paginator(performance_datas, 10)
    if pages.num_pages <= 1:
        performance_datas_list = performance_datas.order_by("create_time")
        data = ''
    else:
        p = int(request.GET.get('page', 1))
        performance_datas_list = pages.page(p)
        left = []
        right = []
        left_has_more = False
        right_has_more = False
        first = False
        last = False
        total_pages = pages.num_pages
        page_range = pages.page_range
        if p == 1:
            right = page_range[p:p + 2]
            if right[-1] < total_pages - 1:
                right_has_more = True
            if right[-1] < total_pages:
                last = True
        elif p == total_pages:
            left = page_range[(p - 10) if (p - 10) > 0 else 0:p - 1]  # 获取左边连续号码页
            if left[0] > 2:
                left_has_more = True  # 如果最左边的号码比2还要大，说明其与第一页之间还有其他页码，因此需要显示省略号，通过 left_has_more 来指示
            if left[0] > 1:  # 如果最左边的页码比1要大，则要显示第一页，否则第一页已经被包含在其中
                first = True
        else:
            left = page_range[(p - 10) if (p - 10) > 0 else 0:p - 1]
            right = page_range[p:p + 1]  # 获取右边连续号码页
            if left[0] > 2:
                left_has_more = True
            if left[0] > 1:
                first = True
            if right[-1] < total_pages - 1:
                right_has_more = True
            if right[-1] < total_pages:
                last = True

        data = {
            'left': left,
            'right': right,
            'left_has_more': left_has_more,
            'right_has_more': right_has_more,
            'first': first,
            'last': last,
            'total_pages': total_pages,
            'p': p
        }
    return render(request, 'show.html', locals())


def show_performance_list(request):
    performance_datas = performanceData.objects.all()
    for i in range(0, len(performance_datas)):
        # todo 记录为空的情况要说明一下
        if performance_datas[i].data is None:
            _id = performance_datas[i].id
            performanceData.objects.get(id=_id).delete()  # 删除空数据记录
    pages = Paginator(performance_datas, 10)
    if pages.num_pages <= 1:
        performance_datas_list = performance_datas.order_by("create_time")
        data = ''
    else:
        p = int(request.GET.get('page', 1))
        performance_datas_list = pages.page(p)
        left = []
        right = []
        left_has_more = False
        right_has_more = False
        first = False
        last = False
        total_pages = pages.num_pages
        page_range = pages.page_range
        if p == 1:
            right = page_range[p:p + 2]
            if right[-1] < total_pages - 1:
                right_has_more = True
            if right[-1] < total_pages:
                last = True
        elif p == total_pages:
            left = page_range[(p - 10) if (p - 10) > 0 else 0:p - 1]  # 获取左边连续号码页
            if left[0] > 2:
                left_has_more = True  # 如果最左边的号码比2还要大，说明其与第一页之间还有其他页码，因此需要显示省略号，通过 left_has_more 来指示
            if left[0] > 1:  # 如果最左边的页码比1要大，则要显示第一页，否则第一页已经被包含在其中
                first = True
        else:
            left = page_range[(p - 10) if (p - 10) > 0 else 0:p - 1]
            right = page_range[p:p + 1]  # 获取右边连续号码页
            if left[0] > 2:
                left_has_more = True
            if left[0] > 1:
                first = True
            if right[-1] < total_pages - 1:
                right_has_more = True
            if right[-1] < total_pages:
                last = True

        data = {
            'left': left,
            'right': right,
            'left_has_more': left_has_more,
            'right_has_more': right_has_more,
            'first': first,
            'last': last,
            'total_pages': total_pages,
            'p': p
        }
    return render(request, 'show.html', context={'performance_datas_list': performance_datas_list, 'data': data})


def delete(request):
    _id = request.GET.get("id")
    print(_id)
    if _id is None:
        return render(request, 'show.html')
    performanceData.objects.get(id=_id).delete()
    performance_datas = performanceData.objects.all()
    performance_datas.order_by("create_time")
    return render(request, 'show.html', locals())


def detail(request):
    _id = request.GET.get("id")
    if _id is None:
        return render(request, 'show.html')
    detail_data = performanceData.objects.get(id=_id).data
    data = json.loads(detail_data)
    return render(request, 'show_detail.html', data)


def addtask(request):
    taskname = request.POST.get('task')
    if taskname is None:
        data = ''
        return HttpResponse(json.dumps(data))
    gameProjects.objects.create(project_name=taskname)
    gameProjects.objects.update()
    tasknames = gameProjects.objects.all().order_by("project_name")
    return render(request, 'base.html', locals())


def show_task(request):
    tasknames = json.loads(serializers.serialize('json', gameProjects.objects.all().order_by("project_name")))
    # data = {}
    data = []
    for i in range(len(tasknames)):
        datas = tasknames[i]['fields']
        data.append(datas['project_name'])
    mydata = ','.join([str(i) for i in data])
    return HttpResponse(mydata)


def archive(request):
    data_id = request.GET.get('str')[:-1].split(',')
    gameprojects = []
    gameproject = json.loads(serializers.serialize('json', gameProjects.objects.all()))
    for key in gameproject:
        dic = {'id': key['pk'],
               'project_name': key['fields']['project_name'],
               'create_time': key['fields']['create_time']
               }
        gameprojects.append(dic)
    if gameprojects is None:
        data = ''
        return HttpResponse(json.dumps(data))
    data = json.dumps({
        "gameprojects": gameprojects,
        "data_id": data_id
    })
    return HttpResponse(data)


def submitarchive(request):
    id_list = request.POST.getlist("ids")  # 获取数据记录id
    arr = request.POST.getlist("arr")  # 获取gameproject id
    re_list = []
    if id_list is None or arr is None:
        return HttpResponse()
    for key in arr:
        game = gameProjects.objects.get(id=int(key))
        # todo 针对已经归档的数据需要剔除掉
        for _id in id_list:
            per_datas = game.game_performance.filter(id=int(_id))
            print(per_datas)
            if not per_datas:
                game.game_performance.add(_id)
            else:
                re_list.append(_id)
    data = 'ok'
    if re_list:
        data = {"data": re_list}
        return HttpResponse(json.dumps(data))
    else:
        return HttpResponse(json.dumps(data))


def show_project_data(request, task_name):
    game = gameProjects.objects.filter(project_name=task_name)
    per_data = json.loads(serializers.serialize('json', game.all().order_by("game_performance")))
    game_performance = []
    per_list = []
    for data in per_data:
        datas = data['fields']
        game_performance = datas['game_performance']
    for game_performance_id in game_performance:
        per = performanceData.objects.get(id=game_performance_id)
        per_list.append(per)
    pages = Paginator(per_list, 10)
    if pages.num_pages <= 1:
        performance_datas_list = per_list
        data = ''
    else:
        p = int(request.GET.get('page', 1))
        performance_datas_list = pages.page(p)
        left = []
        right = []
        left_has_more = False
        right_has_more = False
        first = False
        last = False
        total_pages = pages.num_pages
        page_range = pages.page_range
        if p == 1:
            right = page_range[p:p + 2]
            if right[-1] < total_pages - 1:
                right_has_more = True
            if right[-1] < total_pages:
                last = True
        elif p == total_pages:
            left = page_range[(p - 10) if (p - 10) > 0 else 0:p - 1]  # 获取左边连续号码页
            if left[0] > 2:
                left_has_more = True  # 如果最左边的号码比2还要大，说明其与第一页之间还有其他页码，因此需要显示省略号，通过 left_has_more 来指示
            if left[0] > 1:  # 如果最左边的页码比1要大，则要显示第一页，否则第一页已经被包含在其中
                first = True
        else:
            left = page_range[(p - 10) if (p - 10) > 0 else 0:p - 1]
            right = page_range[p:p + 1]  # 获取右边连续号码页
            if left[0] > 2:
                left_has_more = True
            if left[0] > 1:
                first = True
            if right[-1] < total_pages - 1:
                right_has_more = True
            if right[-1] < total_pages:
                last = True

        data = {
            'left': left,
            'right': right,
            'left_has_more': left_has_more,
            'right_has_more': right_has_more,
            'first': first,
            'last': last,
            'total_pages': total_pages,
            'p': p
        }
    return render(request, 'project.html',
                  context={'performance_datas_list': performance_datas_list, 'data': data, 'task_name': task_name})


def get_together(request):
    id_list = request.GET.getlist("arr")
    project_name = request.GET.get("project_name")
    game_projects = gameProjects.objects.get(project_name=project_name)
    data = {}
    for id in id_list:
        detail_data = game_projects.game_performance.get(id=id).data
        _data = json.loads(detail_data)  # 将json格式数据转化成字典
        data[id] = _data
    if data:
        return HttpResponse(json.dumps(data))
    else:
        msg = 'none'
        return HttpResponse(msg)


def togetherdetail(request):
    return render(request, 'show_together_detail.html')


def export(request):
    arr = request.GET.getlist("arr")
    if arr is None:
        data = 0
        return HttpResponse(data)
    data = {}
    for _id in arr:
        performace_date = json.loads(performanceData.objects.get(id=_id).data)
        _data = {
            "FPS": performace_date["data"]["FPS"],
            "CPU": performace_date["data"]["CPU"],
            "Memory": performace_date["data"]["Memory"]
        }
        data[_id] = _data
    print(data)
    return HttpResponse(json.dumps(data))


def export_report(request):
    if request.method == 'POST':
        from performance import sendEmail
        arr = request.POST.getlist('arr')
        environment_data = request.POST.getlist('environment_data')
        id_list = environment_data[5].split('["')[1].split('"]')[0].split('","')
        # print(id_list)
        project_name = environment_data[6]
        # print(project_name)
        game_projects = gameProjects.objects.get(project_name=project_name)
        data = {}
        for id in id_list:
            detail_data = game_projects.game_performance.get(id=id).data
            _data = json.loads(detail_data)  # 将json格式数据转化成字典
            data[id] = _data
        import base64
        title = ['内存情况', 'CPU占用情况', '帧率情况', ]
        for i in range(len(arr)):
            arr_data = arr[i].split('base64,')[1]
            img_data = base64.b64decode(arr_data)
            image = open(title[i] + '.png', 'wb')
            image.write(img_data)
            image.close()
        sendEmail.struct_email(environment_data,data)
        msg = 200
        return HttpResponse(msg)
